// 在 components 目录下新建 UploadPage.jsx
import { Button, Container, Paper, TextField, Typography, FormControl, InputLabel, Select, MenuItem, Alert } from '@mui/material';
import { 
  Tabs,  
  CssBaseline, 
  Tab 
} from '@mui/material';
import Navbar from '../components/Navbar';
import categoryOptions from './category.json'
import { Link, useLocation } from 'react-router-dom';
import React, { useState, useEffect } from 'react';
import { uploadSeed } from '../api/upload.js'; 
import UploadFileIcon from '@mui/icons-material/UploadFile';
import ImageIcon from '@mui/icons-material/Image';
import {
Grid,
Avatar,
Box,
Chip,
Divider
} from '@mui/material';
import { navigationItems } from '../App';


const Upload=()=> {
  const [category, setCategory] = useState('音乐');
    const [firstType, setFirstType] = useState('');
    const [secondType, setSecondType] = useState('');
    const [thirdType, setThirdType] = useState('');
    const [fourthType, setFourthType] = useState('');
    const [describe,setDescribe] = useState('');
    const [coverImage, setCoverImage] = useState(null);     
    const [coverPreview, setCoverPreview] = useState(null);   
    const [torrentFile, setTorrentFile] = useState(null);
    const [fileError, setFileError] = useState('');

    const [uploading, setUploading] = useState(false);
  const [uploadError, setUploadError] = useState(null);
  const [uploadSuccess, setUploadSuccess] = useState(null);
    const [paymentType, setPaymentType] = useState('free');
    const [priceNum,setPriceNum] = useState('');
    const [price,setPrice] = useState('');
    const [name,setName] = useState('');
    const [size,setSize] = useState('');
  useEffect(() => {
      if (categoryOptions[category]) {
        setFirstType('');
        setSecondType('');
        setThirdType('');
        setFourthType('');
      }
    }, [category]);
     
  // 处理标签的切换逻辑
  const handleFirstTypeToggle = (type) => {
    setFirstType(firstType === type ? '' : type);
  };
  
  const handleSecondTypeToggle = (type) => {
    setSecondType(secondType === type ? '' : type);
  };
  
  const handleThirdTypeToggle = (type) => {
    setThirdType(thirdType === type ? '' : type);
  };
  
  const handleFourthTypeToggle = (type) => {
    setFourthType(fourthType === type ? '' : type);
  };
    
  const location = useLocation()
  const handleCoverChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      setCoverImage(file);
      setCoverPreview(URL.createObjectURL(file));
    }
  };
   const handleAutoRefresh = () => {
    // 3秒后自动刷新页面
    setTimeout(() => {
      window.location.reload();
    }, 3000);
  };
  const handleTorrentFileChange = (e) => {
    const file = e.target.files[0];
    setFileError('');
    
    if (file) {
      if (!file.name.endsWith('.torrent')) {
        setFileError('只能上传.torrent格式的文件');
        setTorrentFile(null);
        e.target.value = null; // 清空文件输入
        return;
      }
      
      setTorrentFile(file);
    }
  };
  
  useEffect(() => {
    if (paymentType === 'free') {
      setPrice('free');
    } else {
      setPrice(priceNum + paymentType);
    }
  }, [paymentType, priceNum]);
  const postUpload = async () => {
    console.log("test");
    if (!torrentFile) {
      setFileError('请选择一个.torrent文件');
      return;
    }
    setUploading(true);
    setUploadError(null);
    setUploadSuccess(null);

    try {
      const formData = new FormData();
      formData.append('name', name);
      formData.append('type', category);
      formData.append('firstType', firstType);
      formData.append('secondType', secondType);
      formData.append('thirdType', thirdType);
      formData.append('fourthType', fourthType);
      formData.append('description', describe);
      formData.append('cost', price);
      if (coverImage) {
        formData.append('coverImage', coverImage);
      }
      formData.append('file', torrentFile);

      const response = await uploadSeed(formData);
      console.log(response);
      // axios 成功的话，直接用 response.data
      setUploadSuccess('上传成功');
      handleAutoRefresh();

    } catch (error) {
      // axios 的错误格式一般是 error.response.data.message
      setUploadError(error.response?.data?.message || error.message || '上传失败');
    } finally {
      setUploading(false);
    }
  };
  const handleRefresh = () => {
  window.location.reload();
};


  return (
    <div className='upload'>
      <CssBaseline />
            <Navbar />
            
              <Container
                      maxWidth="false"
                      sx={{
                        backdropFilter: 'blur(4px)',
                        backgroundColor: 'rgba(255,255,255,0.6)',
                        borderRadius: 3,
                        p: 2,
                        mt: 3,
                      }}
                    >
              
                    <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
                      <Tabs
                          value={location.pathname}
                          indicatorColor="secondary"
                          textColor="secondary"
                          variant="scrollable"
                          scrollButtons="auto"
                          sx={{
                            borderBottom: '2px solid #f3e5f5',
                            mb: 2,
                            '& .MuiTab-root': {
                              transition: 'all 0.3s ease-in-out',
                            },
                            '& .Mui-selected': {
                              color: '#8e24aa',
                              fontWeight: 'bold',
                            },
                            '& .MuiTabs-indicator': {
                              height: 3,
                              backgroundColor: '#ce93d8',
                              borderRadius: 2,
                            }
                          }}
                        >
              
                        {navigationItems.map((item) => (
                          <Tab
                            key={item.path}
                            label={item.label}
                            value={item.path}
                            component={Link}
                            to={item.path}
                            sx={{
                              minWidth: 100,
                              borderRadius: 2,
                              mx: 0.5,
                              transition: 'all 0.3s',
                              color: '#8e24aa',
                              '&:hover': {
                                backgroundColor: '#ffe0f0',
                                color: '#d81b60',
                              },
                              '&.Mui-selected': {
                                fontWeight: 'bold',
                                color: '#d81b60',
                                backgroundColor: '#fff0f5',
                              },
                            }}
                          />
                        ))}
                      </Tabs>
                      </Box>
                    </Container>
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Paper
  elevation={4}
  sx={{
    p: 4,
    borderRadius: '20px',
    background: '#f8f9fc', // 更柔和背景
  }}
>

          <Typography variant="h5" gutterBottom>上传种子</Typography>
          <Grid item xs={12} md={8}>
            {/* 一级 Tabs 分类 */}
            <Tabs
              value={category}
              onChange={(e, newValue) => {
                setCategory(newValue);
              }}
              textColor="primary"
              indicatorColor="primary"
              variant="scrollable"
              scrollButtons="auto"
sx={{
    mb: 2,
    borderRadius: '12px',
    boxShadow: '0 2px 6px rgba(0,0,0,0.05)',
    px: 1,
  }}            >
              {Object.keys(categoryOptions).map((cat) => (
                <Tab
                  key={cat}
                  label={cat}
                  value={cat}
                  sx={{ '&.Mui-selected': { fontWeight: 'bold' } }}
                />
              ))}
            </Tabs>
            <Box 
              display="flex"
              flexWrap="wrap"
              maxWidth="900px"  
              gap={1}
              sx={{ mb: 2 }}
            >
              {/* 二级子分类，每个单独占一行 */}
              <Box display="flex" alignItems="center" flexWrap="wrap" gap={1} sx={{ mb: 2 }}>
                <Typography variant="subtitle1" sx={{ mr: 2, whiteSpace: 'nowrap' }}>
                  {categoryOptions[category]['子分类'][0]}
                </Typography>
                {categoryOptions[category]?.[categoryOptions[category]['子分类'][0]].map((sub) => (
                  <Chip
                    key={sub}
                    label={sub}
                    clickable
                    color={firstType === sub ? 'primary' : 'default'}
                    variant={firstType === sub ? 'filled' : 'outlined'}
                    onClick={() => handleFirstTypeToggle(sub)}
                     sx={{
    borderRadius: '16px',
    fontWeight: 500,
    fontSize: '0.9rem',
    px: 1.5,
    py: 0.5,
    '&.MuiChip-clickable:hover': {
      backgroundColor: '#e3f2fd',
    },
  }}
                  />
                ))}
              </Box>
              <Box display="flex" alignItems="center" flexWrap="wrap" gap={1} sx={{ mb: 2 }}>
                <Typography variant="subtitle1" sx={{ mr: 2, whiteSpace: 'nowrap' }}>
                  {categoryOptions[category]['子分类'][1]}
                </Typography>
                {categoryOptions[category]?.[categoryOptions[category]['子分类'][1]].map((sub) => (
                  <Chip
                    key={sub}
                    label={sub}
                    clickable
                    color={secondType === sub ? 'primary' : 'default'}
                    variant={secondType === sub ? 'filled' : 'outlined'}
                    onClick={() => handleSecondTypeToggle(sub)}
                  />
                ))}
              </Box>
              <Box display="flex" alignItems="center" flexWrap="wrap" gap={1} sx={{ mb: 2 }}>
                <Typography variant="subtitle1" sx={{ mr: 2, whiteSpace: 'nowrap' }}>
                  {categoryOptions[category]['子分类'][2]}
                </Typography>
                {categoryOptions[category]?.[categoryOptions[category]['子分类'][2]].map((sub) => (
                  <Chip
                    key={sub}
                    label={sub}
                    clickable
                    color={thirdType === sub ? 'primary' : 'default'}
                    variant={thirdType === sub ? 'filled' : 'outlined'}
                    onClick={() => handleThirdTypeToggle(sub)}
                  />
                ))}
              </Box>
              <Box display="flex" alignItems="center" flexWrap="wrap" gap={1} sx={{ mb: 2 }}>
                <Typography variant="subtitle1" sx={{ mr: 2, whiteSpace: 'nowrap' }}>
                  {categoryOptions[category]['子分类'][3]}
                </Typography>
                {categoryOptions[category]?.[categoryOptions[category]['子分类'][3]].map((sub) => (
                  <Chip
                    key={sub}
                    label={sub}
                    clickable
                    color={fourthType === sub ? 'primary' : 'default'}
                    variant={fourthType === sub ? 'filled' : 'outlined'}
                    onClick={() => handleFourthTypeToggle(sub)}
                  />
                ))}
              </Box>
            </Box>
          </Grid>
          <form>
            <TextField
              fullWidth
              label="资源名称"
              margin="normal"
              variant="outlined"
              onChange={(e) => setName(e.target.value)}
            />
            <Box sx={{ mt: 2, mb: 2 }}>
              <Button
  variant="outlined"
  component="label"
  startIcon={<UploadFileIcon />}  // 需要 import
  sx={{
    borderRadius: '12px',
    borderColor: '#90caf9',
    color: '#1976d2',
    '&:hover': {
      backgroundColor: '#e3f2fd',
    }
  }}
>
  选择种子文件 (.torrent)

                <input
                  type="file"
                  accept=".torrent"
                  hidden
                  onChange={handleTorrentFileChange}
                />
              </Button>
              {torrentFile && (
                <Typography variant="body2" sx={{ mt: 1 }}>
                  已选择文件: {torrentFile.name}
                </Typography>
              )}
              {fileError && (
                <Alert severity="error" sx={{ mt: 1 }}>
                  {fileError}
                </Alert>
              )}
            </Box>
            
            <TextField
              fullWidth
              label="资源描述"
              margin="normal"
              multiline
              rows={4}
              onChange={(e) => setDescribe(e.target.value)}
            />
            <Box sx={{ mt: 2 }}>
<Button
  variant="outlined"
  component="label"
  startIcon={<ImageIcon />} // 需要 import
  sx={{
    mt: 1,
    borderRadius: '12px',
    borderColor: '#ce93d8',
    color: '#8e24aa',
    '&:hover': {
      backgroundColor: '#f3e5f5',
    }
  }}
>
  上传封面图片

                <input
                  type="file"
                  accept="image/*"
                  hidden
                  onChange={handleCoverChange}
                />
              </Button>

              {coverPreview && (
                <Box
  sx={{
    mt: 2,
    borderRadius: '16px',
    border: '2px dashed #ccc',
    backgroundColor: '#fff',
    p: 2,
    textAlign: 'center',
  }}
>
  <Typography variant="body2" color="textSecondary">预览：</Typography>
  <img
    src={coverPreview}
    alt="封面预览"
    style={{
      maxWidth: '100%',
      height: 'auto',
      marginTop: '8px',
      borderRadius: '12px',
      boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
    }}
  />
</Box>

              )}
            </Box>

            {/* <Box>
              <FormControl
  fullWidth
  margin="normal"
  sx={{ borderRadius: '12px' }}
>

                <InputLabel>支付类型</InputLabel>
                <Select
                  value={paymentType}
                  label="支付类型"
                  onChange={(e) => setPaymentType(e.target.value)}
                >
                  <MenuItem value="free">免费</MenuItem>
                  <MenuItem value="yt">杨桃支付</MenuItem>
                  <MenuItem value="pt">积分支付</MenuItem>
                </Select>
              </FormControl>

              {paymentType !== 'free' && (
                <TextField
                  fullWidth
                  label="价格数量"
                  margin="normal"
                  type="number"
                  onWheel={(e) => e.target.blur()}  
                  onChange={(e) => setPriceNum(Number(e.target.value))}
                />
              )}
            </Box> */}
            <Button
  variant="contained"
  color="primary"
  onClick={postUpload}
  sx={{
    mt: 3,
    py: 1.2,
    fontWeight: 'bold',
    fontSize: '1rem',
    borderRadius: '12px',
    backgroundColor: '#42a5f5',
    '&:hover': {
      backgroundColor: '#1e88e5',
    }
  }}
>
  🚀 提交上传
</Button>
{uploadSuccess && (
  <div 
    className="success-message" 
    onClick={handleRefresh}
    style={{ cursor: 'pointer', color: 'green', fontWeight: 'bold' }}
  >
    {uploadSuccess}
  </div>
)}

          </form>
        </Paper>
      </Container>
    </div>
  );
}
export default Upload